package com.banshou.installs.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import com.banshou.installs.R;
import com.banshou.installs.constant.Config;
import com.banshou.installs.model.dao.PrograssEvent;
import com.banshou.installs.model.dao.ResponseUpdate;
import com.banshou.installs.model.net.Observer;
import com.banshou.installs.model.net.ResponseInfo;
import com.banshou.installs.model.net.RetrofitManager;
import com.banshou.installs.model.net.RetrofitManager2;
import com.banshou.installs.model.net.RxUtil;
import com.banshou.installs.utils.RxBus;
import com.banshou.installs.utils.SharePreUtil;
import com.banshou.installs.utils.ToastUtil;
import com.banshou.installs.utils.UpdateUtil;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.orhanobut.logger.Logger;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by cjq on 2018/1/8.
 * Email: stoic_yb@139.com
 * features:
 */

public class SplshActivity extends BaseActivity {
    private NotificationManager notifyManager;
    private NotificationCompat.Builder builder;


    private String str = "my test1";

    @SuppressLint("CheckResult")
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE
                        , Manifest.permission.READ_PHONE_STATE)
                .subscribe((Boolean aBoolean) -> {
                    if (aBoolean) {
                        Logger.d((System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 30 * 12));
                        checkVersion();
                    }
                });
    }

    private String createToken(String token)
    {
        String tmp = token + ":" + (System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 30 * 12);
        return tmp + ":" + EncryptUtils.encryptMD5ToString(tmp + ":wrenchkey");
    }

    public void onTurn() {
        String aNull = SharePreUtil.getName(this, "NULL");
        if (aNull.equals("NULL")) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
        } else {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        }
    }

    /**
     * 校验版本
     */
    @SuppressLint("CheckResult")
    private void checkVersion() {
        final UpdateUtil updateUtil = new UpdateUtil(this);
        RetrofitManager2.getInstance()
                .create(ResponseInfo.class)
                .getAppVersion(AppUtils.getAppVersionCode(), 5)
                .compose(RxUtil.lifecycle(this))
                .subscribe(new Observer<ResponseUpdate>() {
                    @Override
                    protected void onNextStep(ResponseUpdate responseUpdate) {
                        if (responseUpdate.getUrl().equals("")) {
                            onTurn();
                            return;
                        }
                        final Dialog dialog = new Dialog(SplshActivity.this, R.style.edit_AlertDialog_style);
                        View view = LayoutInflater.from(SplshActivity.this).inflate(R.layout.update_dialog, null);
                        dialog.setContentView(view);
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.show();
                        Button confirm = view.findViewById(R.id.confirm);
                        Button cancel = view.findViewById(R.id.cancel);
                        confirm.setOnClickListener(view3 -> {
                            dialog.cancel();
                            notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//                            Intent resultIntent = new Intent(SplshActivity.this, SplshActivity.class);
//                            PendingIntent resultPendingIntent = PendingIntent.getActivity(
//                                    SplshActivity.this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                String channelId = Config.channId;
                                String channelName = "更新消息";
                                int importance = NotificationManager.IMPORTANCE_HIGH;
                                createNotificationChannel(channelId, channelName, importance);
                            }
                            builder = new NotificationCompat.Builder(SplshActivity.this, Config.channId)
                                    .setSmallIcon(R.mipmap.ic_launcher)
                                    .setContentTitle("安装宝")
                                    .setProgress(100, 0, false)
//                                    .setContentIntent(resultPendingIntent)
                                    .setContentText("下载中");

                            updateUtil.download(Config.BASEURL + responseUpdate.getUrl());
                            ToastUtil.toast("正在下载更新，请稍后");
                            if (!responseUpdate.isForce()) {
                                onTurn();
                            }
                        });
                        cancel.setOnClickListener(view32 -> {
                            if (responseUpdate.isForce()) {
                                finish();
                            } else {
                                onTurn();
                            }
                            dialog.cancel();
                        });
                    }

                    @Override
                    protected void onErrorResult() {

                    }
                });

/**
 * 通知栏更新
 */
        RxBus.getDefault().toObserverable(PrograssEvent.class)
                .subscribe(prograssEvent -> {
                    if (prograssEvent.getStatus().getTotalSize() == prograssEvent.getStatus().getDownloadSize()) {
                        builder.setContentText("下载完成");
                    } else {
                        builder.setContentText("下载中");
                    }
                    builder.setProgress((int) prograssEvent.getStatus().getTotalSize(), (int) prograssEvent.getStatus().getDownloadSize(), false);
                    notifyManager.notify(1, builder.build());
                });
    }

    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        NotificationManager notificationManager = (NotificationManager) getSystemService(
                NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
    }
}
